import { Divider, Tag, Space, Button, message } from 'antd'
import type { Detail } from '../types/Detail'
import { useState, useEffect, useMemo } from 'preact/hooks'
import { Prism } from 'react-syntax-highlighter'
import { atomDark } from 'react-syntax-highlighter/dist/esm/styles/prism'
import Parameters from './Parameters'
import Panel from './common/Panel'

export default function Method({ detail, segment }: { detail: Detail, segment: string }) {
    const [messageApi, contextHolder] = message.useMessage();

    const CopyButton = useMemo(() => ({ code }: { code: string }) => {
        const handleCopy = () => {
            navigator.clipboard.writeText(code)
                .then(() => successCopy('Copy Success'))
                .catch(() => successCopy('Copy Failed'))
        }
        return <Button className='copy-btn' size="small" onClick={handleCopy}>Copy</Button>
    }, [])

    const successCopy = (message: string) => {
        messageApi.open({
            type: 'success',
            content: message,
            className: 'custom-class',
            style: {
                marginTop: '20vh',
            },
        });
    };
    // 代码块组件（避免重复渲染）
    const CodeBlock = useMemo(() =>
        ({ title, code }: { title: string, code: string }) => (
            <>
                <Divider orientation="left" orientationMargin="0">{title}</Divider>
                <div className="code-container">
                    <CopyButton code={JSON.stringify(code, null, 2)} />
                    <Prism
                        language="json"
                        style={atomDark}
                        wrapLongLines
                        showLineNumbers
                    >
                        {code}
                    </Prism>
                </div>
            </>
        ),
        []
    )

    const requestBody = detail.requestBody
    console.log(requestBody)
    return (
        <>
            {contextHolder}
            <Divider orientation="left" orientationMargin="0">{detail.operationId}<Tag style={{ marginLeft: '10px' }}>{detail.tags}</Tag></Divider>
            <p style={{ textAlign: 'left' }}>{detail.summary}</p>

            <Panel label="Parameters">
                <Parameters
                    parameters={detail.parameters}
                    segment={segment}
                />
            </Panel>

            {detail.requestBody && (
                <CodeBlock title={'Request Body'} code={JSON.stringify(detail.requestBody, null, 2)} />
            )}
            <CodeBlock title={'Responses'} code={JSON.stringify(detail.responses, null, 2)} />
            <Space>
                <Button type="primary">Try it out</Button>
                <Button>View Schema</Button>
            </Space>
        </>

    )
}
